import express from "express";
import type { Request, Response } from "express";
import http from "http";
import { resolve } from "path";
// import { socketServer } from "@/utils/websocket";
import { expressjwt } from "express-jwt";

import { ALGORITHM, SECRETKEY } from "@/utils/token";
import { logger } from "@/utils/log"; // 日志方法
import { whitePath } from "@/api/white-path";
import api from "@/api";
const app = express();
const server = http.createServer(app);
// 接收json请求参数
app.use(express.json());
app.use(express.urlencoded({ extended: true })); // extended设置为false接口参数对象校验会报错

// 解析token
app.use(
  expressjwt({ secret: SECRETKEY, algorithms: [ALGORITHM] }).unless({
    path: whitePath,
  })
);

// 请求中间件
app.use((req, res, next) => {
  // logger.log(`请求路径：${req.path}`);
  // logger.log(`请求源：${req.headers.origin || req.headers.host}`);
  // logger.log("query参数：");
  // logger.log(req.query);
  // logger.log("body参数：");
  // logger.log(req.body);
  next();
});

// 开启websocket服务
// socketServer(server);

// 开放静态服务
app.use("/static", express.static(resolve(__dirname, "./static")));

// 开放路由
for (const server in api) {
  const router = api[server];
  app.use(`/${server}`, router);
}

// 错误中间件
app.use((error: Error, req: Request, res: Response, next) => {
  // 如果错误是由token解析失败导致的
  if (error.name === "UnauthorizedError") {
    logger.error({ message: "无效的token", error, res, code: 401 });
    return;
  } else if (error.name == "MulterError") {
    logger.error({
      message: `文件上传失败--${error.message}`,
      error,
      code: 202,
      res,
    });
    return;
  }
  // 如果是其他位置原因导致的错误
  logger.error({ message: "服务器内部错误", error, res, code: 500 });
  next;
});

// 监听端口并开启服务
server.listen(3000, () => {
  logger.log("服务开启成功！服务地址：http://127.0.0.1:3000");
});
